package com.gpscookie.mobile;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Vector;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;


public class DownloadManager implements Runnable {

	private DownloadListener listener = null;
	private boolean running;
	private String  url;
	private byte[] payload = null;
	private boolean isPost = false;
	
	public int upload(DownloadListener who, String what, byte[] data) {
		if (data==null || what==null || data.length<=0) {
			return -1; // error
		}
		if (!running) {
			this.isPost = true;
			this.payload = data;
			this.listener = who;
			url = what;
			Thread t = new Thread(this);
			t.start();
			return 0;
		} else {
			return 1;	// busy
		}		
	}
	
	public int download(DownloadListener who, String what) {
		if (!running) {
			this.isPost = false;
			this.listener = who;
			url = what;
			Thread t = new Thread(this);
			t.start();
			return 0;
		} else {
			return 1;	// busy
		}
	}
	
	/* (non-Javadoc)
	 * @see java.lang.Runnable#run()
	 */
	public void run() {
		ByteArrayOutputStream buffer = null;
		HttpConnection connection  = null;
		InputStream    inputStream = null;
		
		running = true;
		try {
			buffer = new ByteArrayOutputStream();
			
			connection  = (HttpConnection) Connector.open(this.url);

			// Post the data
			if (isPost) {
				connection.setRequestMethod(HttpConnection.POST);
				connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
				connection.setRequestProperty("Content-Length", String.valueOf(payload.length));
				OutputStream stream = connection.openOutputStream();
				stream.write(payload);
				stream.flush();				
			}
			
			int rc = connection.getResponseCode();
			if (rc == HttpConnection.HTTP_OK) {
				inputStream = connection.openInputStream();				
				long length = connection.getLength();
				byte[] data = new byte[512];
				int total = 0x00;
				int read  = -1;
				do {
					read = inputStream.read(data);
					if (read > 0x00) {
						total += read;
						buffer.write(data, 0x00, read);
						int percent = 0;
						if (length > 0 ) {
							percent = (int)(total * 100 / length);
						} else {
							percent = 42;	// The answer to everything.
						}
						this.listener.downloadStatus(percent);
					}
				} while (read != -1);				
			}			
		} catch (IOException e) {
			this.listener.downloadError(e);
		} finally {	
			this.listener.downloadCompleted(buffer.toByteArray());
			try {				
				inputStream.close();
				connection.close();
			} catch (Exception e) {
				this.listener.downloadError(e);
			}
		}
		running = false;
	}
}
